
// 功能：设置cookie
// 参数：键，值，有效时长（天数）
function setCookie(key, value, date) {
    let d = new Date();
    d.setDate(d.getDate() + date);

    document.cookie = `${key}=${value};expires=${d};path=/`;
}


// 功能：删除cookie
// 参数：删除的键名
function removeCookie(key) {
    setCookie(key, 'beybey', -1);
}

// 功能：获取指定键的cookie
// 参数：键名
function getCookie(key) {
    let cookieStr = document.cookie;
    let initArr = cookieStr.split('; ');
    for (let i in initArr) {
        if (initArr[i].startsWith(key + '=')) {
            return initArr[i].split('=')[1];
        }
    }
}

// 判断是否是第一次登陆
function isFirstLogin() {
    let cookie = getCookie('username');
    if (cookie) {
        $('.topyou1').css("display","block").html(`
                    <a class="topyoutu" href="javascript:;">
                        <img src="../imges/indeximg/yx/Lillia.png" alt="javascript:;">
                    </a>
                    <b class="mingzi"><a href="">${cookie}</a></b>
                    <p class="topyouzi"><a href="./index.html" target="_blank">退出</a></p>
        `);
        $(".topyou").css("display","none")
    }
}
isFirstLogin()
// 点击退出登录按钮退出登录并跳转
function logout() {
    $('.topyou1').on('click', '.topyouzi', function () {
        removeCookie('username');
        $(".topyou").css("display","block")
        location.reload(true);
    });
}
logout()


$(".shuliang").on("click",".jia",function(){
    let sum = $(".jia").prev().val();
        sum++;
        $(".jia").prev().val(sum);
})

$(".shuliang").on("click",".jian",function(){
    let num = $(this).next().val();
        num--;
        if (num < 1) {
            num = 1;
        }
        $(this).next().val(num);
})




//////////////////获取商品页发送的数据渲染到页面
console.log(location.search.split('=')[1])
$(function () {
    getGoodsInfo()
})
function getGoodsInfo() {
    $.get('../goodsAndShoppingCart/getGoodsInfo.php', { goodsId: location.search.split('=')[1] }, function (data) {
        let arr = JSON.parse(data);
        let str = `
                <li><img src="${arr.beiyong1}"></li>
                <li><img src="${arr.beiyong2}"></li>
                <li><img src="${arr.beiyong3}"></li>
                <li><img src="${arr.beiyong4}"></li>
                `
        $('#box .huan').html(str)
        $("#leftbox").css("background-image", `url(${arr.beiyong1})`)
        $("#rightbox").css("background-image", `url(${arr.beiyong1})`)
        $(".twoyou h2").html(arr.goodsName)
        $(".jiage .s1").html((arr.goodsDesc))
        $(".jiage .s2").html((arr.goodsPrice) + (arr.beiyong5))
    })
}
////////////添加购物车
$(".twoyou .goumai").on("click", function () {
    console.log(getCookie('username'), location.search.split('=')[1],$(".i1").val());

    $.post('../goodsAndShoppingCart/addShoppingCart.php', { 'vipName': getCookie('username'), 'goodsId': location.search.split('=')[1], 'goodsCount': $(".i1").val() }, function (data) {
        if (data == '1') {
            alert("添加成功");
        } else {
            alert("添加失败")
        }
    })
})

//---------------------------添加商品评论--------------------------------------------
$(".anniu").on("click", function () {
    daddComment()
    $(".pinglun").val("")
})
function daddComment() {
    $.post(
        '../goodsAndShoppingCart/addComment.php',
        {
            'vipName': getCookie('username'),
            "goodsId": location.search.split('=')[1],
            "content": $(".pinglun").val()
        },
        function (del) {
            console.log(del);
        }
    )
}
////////////////获取商品评论列表
getComment()
function getComment() {
    $.get(
        '../goodsAndShoppingCart/getComment.php',
        {
            "goodsId": location.search.split('=')[1],
            "pageCount": "4",
            "pageIndex": "1"
        },
        function (del) {
            console.log(del);
            let arr = JSON.parse(del)
            console.log(arr);
            let arr1 = JSON.parse(arr.data)
            console.log(arr1);
            let str = ''
            arr1.forEach(function(item,index){
                str+=`<li>
                <h2>${item.vipName}</h2>
                <p class="p2">${item.content}</p>
                <p class="p1">${item.commentTime}</p>
            </li>`
            })
            $(".three .ul11").html(str)
        }
        
    )}
    






$("#leftbox").on("mousemove", function (e) {
    let l = e.pageX - $("#box").offset().left - $(".huan").innerWidth() - $("#mask").outerWidth() / 2;
    let t = e.pageY - $("#box").offset().top - $("#mask").outerHeight() / 2;
    if (l <= 0) {
        l = 0
    }
    if (l >= $("#leftbox").innerWidth() - $("#mask").outerWidth()) {
        l = $("#leftbox").innerWidth() - $("#mask").outerWidth()
    }
    if (t <= 0) {
        t = 0
    }
    if (t >= $("#leftbox").innerWidth() - $("#mask").outerWidth()) {
        t = $("#leftbox").innerWidth() - $("#mask").outerWidth()
    }
    $("#mask").css("left", l + "px")
    $("#mask").css("top", t + "px")

    // 计算比例
    let lvx = $("#leftbox").innerWidth() / $("#mask").outerWidth()
    let lvy = $("#leftbox").innerHeight() / $("#mask").outerHeight()

    $("#rightbox").css("background-position-x", -lvx * l + "px")
    $("#rightbox").css("background-position-y", -lvy * t + "px")

})
$("#leftbox").hover(function () {
    $("#mask").show()
    $("#rightbox").show()
}, function () {
    $("#mask").hide()
    $("#rightbox").hide()
})


$(".huan").on("click","li",function(){
    $(this).addClass("active").siblings("li").removeClass("active")
    $("#leftbox").css("background-image",`url(${$(this).find("img").prop("src")})`)
    $("#rightbox").css("background-image",`url(${$(this).find("img").prop("src")})`)
})
